﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using MM.DBUtility;
using MM.Common;

namespace WebMMS.Manager
{
    public partial class RuleManager : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session["CurUser"] == null)
                {
                    Response.Redirect("~/Login.aspx");
                    return;
                }
                if (!IsPostBack)
                {
                    BinddlPID(ref ddlPID);
                    ddlPID.Items.Insert(0, new ListItem("全部", "-1"));
                    BindddlAppID(ref ddlAppID);
                    ddlAppID.Items.Insert(0, new ListItem("全部", "-1"));
                    BindddlTaskType(ref ddlTaskType);
                    ddlTaskType.Items.Insert(0, new ListItem("全部", "-1"));

                    AspNetPager1.CurrentPageIndex = 1;
                    GVDataBind();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #region DDL Bind
        private void BinddlPID(ref DropDownList ddl)
        {
            ddl.DataSource = DbHelperSql.Query("SELECT PID,PValue FROM T_Pinfo WITH(NOLOCK) ").Tables[0];
            ddl.DataValueField = "PID";
            ddl.DataTextField = "PValue";
            ddl.DataBind();
        }
        private void BindddlAppID(ref DropDownList ddl)
        {
            ddl.DataSource = DbHelperSql.Query("SELECT APPID,APPValue FROM T_APPinfo WITH(NOLOCK) ").Tables[0];
            ddl.DataValueField = "APPID";
            ddl.DataTextField = "APPValue";
            ddl.DataBind();
        }
        private void BindddlTaskType(ref DropDownList ddl)
        {
            ddl.DataSource = DbHelperSql.Query("SELECT ID,Value FROM T_TaskType WITH(NOLOCK) ").Tables[0];
            ddl.DataValueField = "ID";
            ddl.DataTextField = "Value";
            ddl.DataBind();
        }
        #endregion
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                AspNetPager1.CurrentPageIndex = 1;
                GVDataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected void btnON_Click(object sender, EventArgs e)
        {
            try
            {
                string strIDs = UpdateIDs(hdfBoxValues.Value);
                if (!string.IsNullOrEmpty(strIDs))
                {
                    MM.DBUtility.DbHelperSql.ExecuteSql(string.Format("UPDATE T_Rule SET Status=1 WHERE ID IN ({0})", strIDs));
                    MM.Common.Common.PageStartAlert(this.Page, "状态更新成功！");
                    GVDataBind();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected void btnOff_Click(object sender, EventArgs e)
        {
            try
            {
                string strIDs = UpdateIDs(hdfBoxValues.Value);
                if (!string.IsNullOrEmpty(strIDs))
                {
                    MM.DBUtility.DbHelperSql.ExecuteSql(string.Format("UPDATE T_Rule SET Status=0 WHERE ID IN ({0})", strIDs));
                    MM.Common.Common.PageStartAlert(this.Page, "状态更新成功！");
                    GVDataBind();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected void btnDeleteAll_Click(object sender, EventArgs e)
        {
            try
            {
                string strIDs = UpdateIDs(hdfBoxValues.Value);
                if (!string.IsNullOrEmpty(strIDs))
                {
                    MM.DBUtility.DbHelperSql.ExecuteSql(string.Format("DELETE FROM T_Rule WHERE ID IN ({0})", strIDs));
                    MM.Common.Common.PageStartAlert(this.Page, "删除成功！");
                    GVDataBind();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private string UpdateIDs(string IDs)
        {
            if (IDs.Contains(","))
                IDs = IDs.Remove(IDs.LastIndexOf(","));

            return IDs;
        }
        private void GVDataBind()
        {
            string strSQL = "SELECT a.ID,a.Pid,a.Appid,a.TaskType,CAST(a.TimeFrom AS VARCHAR(2))+'-'+CAST(a.TimeTo AS VARCHAR(2)) AS Timer,a.NotificationID,a.TasklIDs,a.Pcount,a.IsNext,a.Status,a.CreateTime,b.PValue,c.APPValue,d.Value as TypeName FROM T_Rule a,T_Pinfo b,T_APPinfo c,T_TaskType d WITH(NOLOCK) WHERE a.Pid=b.PID AND a.Appid=c.APPID AND a.TaskType=d.ID ";
            if (!"-1".Equals(ddlPID.SelectedValue))
                strSQL += string.Format(" AND a.Pid='{0}'", ddlPID.SelectedValue);
            if (!"-1".Equals(ddlAppID.SelectedValue))
                strSQL += string.Format(" AND a.Appid='{0}'", ddlAppID.SelectedValue);
            if (!"-1".Equals(ddlTaskType.SelectedValue))
                strSQL += string.Format(" AND a.TaskType={0}", ddlTaskType.SelectedValue);
            if (!string.IsNullOrEmpty(inputDateFrom.Value) && !string.IsNullOrEmpty(inputDateTo.Value))
                strSQL += string.Format(" AND a.CreateTime BETWEEN '{0}' AND '{1}' ", inputDateFrom.Value, Convert.ToDateTime(inputDateTo.Value).AddDays(1).ToString("yyyy-MM-dd"));

            string strOrder = " ORDER BY a.CreateTime DESC";

            AspNetPager1.RecordCount = DbHelperSql.GetSingle("SELECT COUNT(1) FROM (" + strSQL + ") AS B").ToIntOr();

            if (AspNetPager1.CurrentPageIndex == 1)
                strSQL = string.Format(strSQL.Replace("SELECT ", "SELECT TOP {0} "), AspNetPager1.PageSize) + strOrder;
            else
                strSQL = string.Format("SELECT TOP {0} * FROM ({1}) AS F WHERE rn BETWEEN {2} AND {3}", AspNetPager1.PageSize, strSQL.Replace("SELECT ", string.Format("SELECT row_number() over({0}) rn, ", strOrder)), (AspNetPager1.CurrentPageIndex - 1) * AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex * AspNetPager1.PageSize - 1);

            DataSet ds = MM.DBUtility.DbHelperSql.Query(strSQL);
            GVinfo.DataSource = ds;
            GVinfo.DataBind();
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            GVDataBind();
        }
        protected void GVinfo_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
            {
                Label lbTasklIDs = (Label)e.Row.FindControl("lbTasklIDs");
                string strTemp = string.Empty;
                string strID = ((HiddenField)e.Row.FindControl("hsfID")).Value;
                if (!string.IsNullOrEmpty(strID))
                {
                    DataTable dt = DbHelperSql.Query(string.Format("SELECT * FROM T_Notification WITH(NOLOCK) WHERE ID={0}", strID)).Tables[0];
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        strTemp = dt.Rows[0]["Title"].ToString() + "(" + dt.Rows[0]["Msg"].ToString() + ")";
                    }
                }
                else
                {
                    strID = lbTasklIDs.Text.Trim();
                    if (!string.IsNullOrEmpty(strID))
                    {
                        DataTable dt = DbHelperSql.Query(string.Format("SELECT * FROM T_Task WITH(NOLOCK) WHERE ID IN ({0})", strID)).Tables[0];
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            foreach (DataRow row in dt.Rows)
                            {
                                strTemp += row["Name"].ToString() + "(" + row["Value"].ToString() + ");";
                            }
                        }
                    }
                }
                if (strTemp.Length > 80)
                {
                    lbTasklIDs.Text = strTemp.Substring(0, 80);
                }
                else lbTasklIDs.Text = strTemp;
                lbTasklIDs.ToolTip = strTemp;

                Label lbStatus = (Label)e.Row.FindControl("lbStatus");
                string strStatus = lbStatus.Text;
                if (strStatus.Equals("0"))
                    lbStatus.Text = "关闭";
                else if (strStatus.Equals("1"))
                    lbStatus.Text = "开启";

                Label lbIsNext = (Label)e.Row.FindControl("lbIsNext");
                string strIsNext = lbIsNext.Text;
                if (strIsNext.Equals("0"))
                    lbIsNext.Text = "否";
                else if (strIsNext.Equals("1"))
                    lbIsNext.Text = "是";
            }
        }
        protected void GVinfo_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                string strID = ((HiddenField)GVinfo.Rows[e.RowIndex].FindControl("HF2")).Value;
                DbHelperSql.ExecuteSql(string.Format("DELETE FROM T_Rule WHERE ID={0}", strID));
                MM.Common.Common.PageStartAlert(this.Page, "删除成功！");
                AspNetPager1.CurrentPageIndex = 1;
                GVDataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}